<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item  :to="{ path: '/fileList' }">
          <i class="el-icon-lx-file"></i> 我的文件
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <i class="el-icon-lx-calendar"></i> 文件上传
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="container">
      <el-radio-group v-model="fileTypeRadio" style="margin-bottom: 30px; margin-left: 30px">
        <el-radio-button label="1">本地文件</el-radio-button>
        <el-radio-button label="2">数据库表</el-radio-button>
      </el-radio-group>

      <el-form
          v-if="fileTypeRadio === '1'"
          :model="csvForm"
          :rules="rules"
          ref="formRef"
          label-width="120px"
      >

        <el-form-item label="上传文件" required>
          <!-- accept接收文件类型,auto-upload:false 关闭自动上传,drag 允许拖动，name=file,上传文件的字段名           -->
          <!-- file-list:接收文件上传的数组,before-upload:配合accept属性,检查文件类型、后缀,before-remove：删除提醒           -->
          <!-- on-change:获取文件，将文件保存在fileList里;limit:最多上传文件数           -->
          <el-upload
              ref="uploadRef"
              accept='text/csv'
              :auto-upload=false
              drag
              name="file"
              :file-list="fileList"
              :before-upload="beforeUploadFile"
              :before-remove="beforeRemoveFile"
              :on-change="getFile"
              :on-exceed="handleExceed"
              :limit="1"
              class="upload-demo"
              style="width: 500px;"
              >
            <i class="el-icon-upload"></i>
            <div style="height:100px; width:100%;">
              <el-button icon="upload" style="border:0">点击上传或者拖拽文件上传</el-button>
            </div>
          </el-upload>

          <span slot="tip">{{message}}</span>
        </el-form-item>

        <el-form-item label="文件重命名" prop="fileName" style="width: 480px;">
          <el-input placeholder="请输入上传后的文件名" v-model="csvForm.fileName">
            <template #append>.csv</template>
          </el-input>
        </el-form-item>

        <!--    操作：      -->
        <el-form-item>
          <el-button
              type="primary"
              @click="submitForm(formRef,uploadRef)"
          >立即创建</el-button>

          <el-button
              @click="resetForm(formRef,uploadRef)"
          >重置</el-button>
          <div>提示：若有字段内容为中文，请设置为UTF-8编码格式。</div>
        </el-form-item>
      </el-form>

      <el-form
              v-if="fileTypeRadio === '2'"
              :model="tableForm"
              :rules="rules"
              ref="formRef"
              label-width="120px"
      >

        <el-form-item label="数据库地址" required style="width: 480px;">
          <el-input placeholder="请输入数据库ip地址" v-model="tableForm.address"></el-input>
        </el-form-item>

        <el-form-item label="用户名" required style="width: 480px;">
          <el-input placeholder="请输入数据库用户名" v-model="tableForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" required style="width: 480px;">
          <el-input type="password" placeholder="请输入数据库密码" v-model="tableForm.password"></el-input>
        </el-form-item>

        <el-form-item label="数据表名" required style="width: 480px;">
          <el-input placeholder="请输入数据库表名" v-model="tableForm.tableName"></el-input>
        </el-form-item>

        <el-form-item label="文件重命名" prop="fileName" style="width: 480px;">
          <el-input placeholder="请输入上传后的文件名" v-model="tableForm.fileName">
            <template #append>.csv</template>
          </el-input>
        </el-form-item>

        <!--    操作：      -->
        <el-form-item>
          <el-button
                  type="primary"
                  @click="submitTableForm"
          >立即创建</el-button>

          <el-button
                  @click="resetTableForm"
          >重置</el-button>
          <div>提示：若有字段内容为中文，请设置为UTF-8编码格式。</div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus"
import {UploadFile} from "../../api/file";

export default {
  name: "Upload",
  setup() {
    //表单，不要和ref重名
    const csvForm= reactive({
      fileName: '',
    });
    //DOM元素
    const formRef=ref('formRef');
    const uploadRef=ref('upload');
    const message= '请上传csv格式的文件';
    //文件列表
    let fileList= [];

    //校验规则
    const rules = reactive({
      fileName:
          [
            {
              max:64,
              message: '文件名最多64个字符!',
              trigger:  'blur',
            },
            {
              required: true,
              message: '必须填写文件名!',
              trigger:  'blur',
            }
          ]
    })

    //————————————————————————————————方法区——————————————————————————————————————————————

    //文件上传后，保存在数组fileList里
    function getFile(file, files) {
      fileList = files;
    }

    //提交表单
    const submitForm = async (formEl,uploadEl) => {
      if (!formEl || !uploadEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          if (fileList.length <= 0) {
            ElMessage.error("请先上传1个文件！");
            return;
          }

          //用于放数据  FormData类型
          let formData= new FormData();
          //将表单内其他内容添加进formData
          formData.append('fileName', csvForm.fileName+'.csv')
          formData.append('file', fileList[0].raw);
          formData.append('userId', localStorage.getItem("ms_userId"))

          //调用接口，提交即可
          ElMessage.success('文件名校验成功!请求已发送,请稍候.')
          UploadFile(formData).then(res => {
            console.log(res)
            fileList=[]
            csvForm.fileName=''
            formEl.resetFields()
            uploadEl.clearFiles()
            if (res.msg === '成功')
            {
              ElMessageBox({
                title: '文件上传',
                message: `文件: ${csvForm.fileName}上传成功`,
                confirmButtonText: '确定',
                beforeClose: (action, instance, done) => {
                  if (action === 'confirm') {
                    instance.confirmButtonLoading = true
                    instance.confirmButtonText = 'Loading...'
                    setTimeout(() => {
                      instance.confirmButtonLoading = false
                      done()
                    } ,200)
                  } else {
                    done()
                  }
                },
              })
            }
            else
              {
                console.log(res);
                ElMessage.error("上传失败!:"+res.msg);
              }
          })
          console.log(csvForm.fileName);
        }
        else {
          ElMessage.error('校验失败!')
          console.log(fields)
        }
      })
    }

    //重置表单
    function resetForm(formEl,uploadEl){
      fileList=[]
      if (!formEl || !uploadEl) return
      formEl.resetFields()
      uploadEl.clearFiles()
    }

    //判断后缀是否符合要去
    function isFileExtensionRight(extension){
      return extension === 'csv' || extension === 'sas';
    }

    //上传前,配合accept属性,检查文件类型、后缀
    function beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (isFileExtensionRight(extension)) {
        ElMessage.warning('文件类型不对,目前只接受csv类型的文件'); //控制文件类型
        return false
      }
    }

    //移除文件时的提醒
    function beforeRemoveFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (!isFileExtensionRight(extension)) return;

      return ElMessageBox({
        title: '移除待上传文件?',
        message: `确定要删除文件: ${file.name} 吗?`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = 'Loading...'
            setTimeout(() => {
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
              }, 125)
            }, 125)
          } else {
            done()
          }
        },
      })
    }

    //超限制
    function handleExceed(files, fileList) {
      ElMessage.warning("目前只能上传一个包")
    }

    return{
      csvForm,
      rules,
      message,
      fileList,
      formRef,
      uploadRef,
      submitForm,
      resetForm,
      getFile,
      beforeUploadFile,
      beforeRemoveFile,
      handleExceed,
    }
  },

  data() {
    return {
      fileTypeRadio: '1',
      tableForm: [{
        address: "",
        username: "",
        password: "",
        tableName: "",
        fileName: ""
      }]
    }
  },

  methods: {
    submitTableForm() {
      const ms_username = localStorage.getItem("ms_username");



    },

    resetTableForm() {
      this.tableForm.address = "";
      this.tableForm.username = "";
      this.tableForm.password = "";
      this.tableForm.tableName = "";
      this.tableForm.fileName = "";
    }

  }
}
</script>

<style scoped>

</style>
